import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DatePipe } from '@angular/common';
import { differenceInCalendarDays } from 'date-fns';

@Component({
  selector: 'app-drug-use-analysis',
  templateUrl: './drug-use-analysis.component.html',
  styleUrls: ['./drug-use-analysis.component.scss'],
  providers: [
    DatePipe
  ]
})
export class DrugUseAnalysisComponent implements OnInit {
  today = new Date();
  currentMonth = `${new Date().getFullYear()}-${new Date().getMonth() + 1}-1`;
  searchParams = {
    start_date: this.datePipe.transform(this.currentMonth, 'yyyy-MM-dd HH:mm:ss'),
    end_date: this.datePipe.transform(this.today, 'yyyy-MM-dd HH:mm:ss'),
    doctor: '全部',
    department: '全部',
    type: '全部',
    guijing: '全部',
    xingwei: '全部',
    '病人性质': '全部'
  };
  anySearchRes: any = {
  };
  resultsObj = null;
  keshiOptions = [];
  yishengOptions = [];
  guijingOptions = [];
  yaoxingOptions = [];
  listOfOption = ['全部', 'a10', 'c12'];
  zhengxingOptions: any;
  yinpianOptions: any;
  zhongyaoyinOptions: any;
  gongxiaoTableData = {};
  zhongshiyongOptions: any;
  xiedingfangOptions: any;
  jingdianfangOptions: any;
  mingguiyaoOptions: any;
  moreGongxiaoTableData = true;
  currentClickName: any;
  constructor(public http: HttpClient, public datePipe: DatePipe) {
   }
   disabledDate = (current: Date): boolean => {
    // Can not select days before today and today
    return differenceInCalendarDays(current, this.searchParams['start_date']) < 0 || differenceInCalendarDays(current, this.searchParams['start_date']) === 0;
  }

   /**
   * @description 搜索方法
   */
  onSubmit() {
    this.searchParams.start_date = this.datePipe.transform(this.searchParams['start_date'], 'yyyy-MM-dd HH:mm:ss');
    this.searchParams.end_date = this.datePipe.transform(this.searchParams['end_date'], 'yyyy-MM-dd HH:mm:ss');

    this.anySearchRes = {};
    this.anySearchRes = JSON.parse(JSON.stringify(this.searchParams));
    if (this.anySearchRes['guijing'] instanceof Array) {
      this.anySearchRes['guijing'] = this.anySearchRes['guijing'].join(' ');
    }
    if (this.anySearchRes['xingwei'] instanceof Array) {
      this.anySearchRes['xingwei'] = this.anySearchRes['xingwei'].join(' ');
    }
    const params = {
      params: this.anySearchRes
    };
    this.http.get(window.API_ROOT + 'api/statistics/medicine', params).toPromise().then((res: any) => {
      console.log(res);
      this.resultsObj = res.data;

      this.createZhengxing();
      this.createYinpian();
      this.createZhongyaoyin();
      this.getGongxiaofenxi();
      this.createZhongshiyong();
      this.createXiedingfang();
      this.createJingdianfang();
      this.createMingguiyao();
    });
  }
   /**
   * @description 获取科室
   */
  getKeshi() {
    const params = {
      params: {
        value: ''
      }
    };
    this.http.get(window.API_ROOT + 'api/recipes/departments', params).toPromise().then((res: any) => {
      console.log(res);
      this.keshiOptions = res.data;
    });
  }
   /**
   * @description 获取医生
   */
  getYisheng() {
    const params = {
      params: {
        '科室': this.searchParams['department']
      }
    };
    this.http.get(window.API_ROOT + 'api/recipes/doctors', params).toPromise().then((res: any) => {
      console.log(res);
      this.yishengOptions = res.data;
    });
  }

  /**
   * @description 获取归经
   */
  getFuijing() {
    const params = {
      params: {
        value: ''
      }
    };
    this.http.get(window.API_ROOT + 'api/recipes/guijings', params).toPromise().then((res: any) => {
      console.log(res);
      this.guijingOptions = res.data;
    });
  }

   /**
   * @description 获取药性
   */
  getYaoxing() {
    const params = {
      params: {
        value: ''
      }
    };
    this.http.get(window.API_ROOT + 'api/recipes/xingweis', params).toPromise().then((res: any) => {
      console.log(res);
      this.yaoxingOptions = res.data;
    });
  }

  /**
   * @description 证型分布
   */
  createZhengxing() {
    const data = this.resultsObj['证型分布/饮片使用排名-饮片'].data;
    let total = 0;
    data.forEach(element => {
      total +=  element.value;
    });
    this.zhengxingOptions = {
      tooltip: {
      },
      color: ['#010066'],
      grid: {
        left: '2%',
        right: '24%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        splitLine: { show: false }, // 改设置不显示坐标区域内的y轴分割线
        show: true,
        axisTick: {
          show: false
        },
        axisLabel: {
          show: false
        }
      },
      yAxis: {
        type: 'category',
        splitLine: { show: false }, // 改设置不显示坐标区域内的y轴分割线
        // data: ['配伍禁忌', '药物超标', '药物重复'],
        axisTick: {
          show: false
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#000',
            fontSize: 16
          }
        },
        data: this.resultsObj['证型分布/饮片使用排名-证型'].name
      },
      series: [
        {
          type: 'bar',
          barWidth: 30,
          data: this.resultsObj['证型分布/饮片使用排名-证型'].data,
          // data: [12, 23, 14],
          itemStyle: {
            normal: {
              label: {
                show: true,
                position: 'right',
                formatter: function(v: any) {
                  const val = v.data.value;
                  const temp: any = ((val / total) * 100).toFixed(2) ;
                  return val + ' 占总数' +  temp  + '%';
              },
                textStyle: { // 数值样式
                  color: 'black',
                  fontSize: 16
                }
              }
            }
          }
        }
      ]
    };
  }

  /**
   * @description 饮片
   */
  createYinpian() {
    const data = this.resultsObj['证型分布/饮片使用排名-饮片'].data;
    let total = 0;
    data.forEach(element => {
      total +=  element.value;
    });
    this.yinpianOptions = {
      tooltip: {
      },
      color: ['#FFCC00'],
      grid: {
        left: '2%',
        right: '24%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        splitLine: { show: false }, // 改设置不显示坐标区域内的y轴分割线
        show: true,
        axisTick: {
          show: false
        },
        axisLabel: {
          show: false
        }
      },
      yAxis: {
        type: 'category',
        splitLine: { show: false }, // 改设置不显示坐标区域内的y轴分割线
        // data: ['配伍禁忌', '药物超标', '药物重复'],
        axisTick: {
          show: false
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#000',
            fontSize: 16
          }
        },
        data: this.resultsObj['证型分布/饮片使用排名-饮片'].name
      },
      series: [
        {
          type: 'bar',
          barWidth: 30,
          data: this.resultsObj['证型分布/饮片使用排名-饮片'].data,
          // data: [12, 23, 14],
          itemStyle: {
            normal: {
              label: {
                show: true,
                position: 'right',
                formatter: function(v: any) {
                  const val = v.data.value;
                  const temp: any = ((val / total) * 100).toFixed(2) ;
                  return val + ' 占总数' +  temp  + '%';
              },
                textStyle: { // 数值样式
                  color: 'black',
                  fontSize: 16
                }
              }
            }
          }
        }
      ]
    };
  }

  /**
   * 饼图事件
   */
  onChartEvent(event) {
    console.log(event);
    this.currentClickName = event.data.name;
    this.moreGongxiaoTableData = true;
    this.getGongxiaofenxi();
  }
  /**
   * @description 中药饮片性味
   */
  createZhongyaoyin() {
    this.zhongyaoyinOptions = {
    tooltip : {
        trigger: 'item',
        formatter: '{b} :{d}%'
    },
    series : [
        {
            name: '姓名',
            type: 'pie',
            radius : '55%',
            center: ['40%', '50%'],
            data: this.resultsObj['中药饮片性味、功效分析排名'].data,
            // data: [
            //   {name: 'ce', value: 23},
            //   {name: 'ce2', value: 83}
            // ],
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'right',
                  formatter: '{b} :{d}%',
                  textStyle: { // 数值样式
                    color: 'black',
                    fontSize: 16
                  }
                }
              },
                emphasis: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
    ]
    };
  }

  /**
   * @description 功效分析表格
   */
  getGongxiaofenxi() {
    // console.log(this.currentClickName, 'name');
    this.moreGongxiaoTableData = !this.moreGongxiaoTableData;
    if (this.currentClickName) {
      if (!this.moreGongxiaoTableData) {
        this.gongxiaoTableData = JSON.parse(JSON.stringify(this.resultsObj['中药饮片性味、功效分析排名-子表']));
        if (JSON.stringify(this.resultsObj['中药饮片性味、功效分析排名-子表']['bodys']) !== '[]') {
          this.gongxiaoTableData['bodys'] = JSON.parse(JSON.stringify(this.resultsObj['中药饮片性味、功效分析排名-子表']['bodys'][this.currentClickName].slice(0, 5)));
        } else {
          this.gongxiaoTableData = JSON.parse(JSON.stringify(this.resultsObj['中药饮片性味、功效分析排名-子表']));
          this.gongxiaoTableData['bodys'] = [];
        }
      } else {
        if (JSON.stringify(this.resultsObj['中药饮片性味、功效分析排名-子表']['bodys']) !== '[]') {
          this.gongxiaoTableData = JSON.parse(JSON.stringify(this.resultsObj['中药饮片性味、功效分析排名-子表']));
          this.gongxiaoTableData['bodys'] = JSON.parse(JSON.stringify(this.resultsObj['中药饮片性味、功效分析排名-子表']['bodys'][this.currentClickName]));
        } else {
          this.gongxiaoTableData = JSON.parse(JSON.stringify(this.resultsObj['中药饮片性味、功效分析排名-子表']));
          this.gongxiaoTableData['bodys'] = [];
        }
      }

    } else {
      this.gongxiaoTableData = JSON.parse(JSON.stringify(this.resultsObj['中药饮片性味、功效分析排名-子表']));
      this.gongxiaoTableData['bodys'] = [];
    }
  }

  /**
   * @description 中成药使用排名 图
   */
  createZhongshiyong() {
    this.zhongshiyongOptions = {
      tooltip: {
      },
      color: ['#C0504E', '#FFC000', '#01B0F1'],
      grid: {
        left: '2%',
        right: '16%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        boundaryGap: [0, 0.01],
        show: false
      },
      yAxis: {
        type: 'category',
        splitLine: { show: false }, // 改设置不显示坐标区域内的y轴分割线
        // data: ['配伍禁忌', '药物超标', '药物重复'],
        axisTick: {
          show: false
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#000',
            fontSize: 16
          }
        },
        data: this.resultsObj['中成药使用排名'].name
      },
      series: [
        {
          type: 'bar',
          barWidth: 30,
          data: this.resultsObj['中成药使用排名'].data,
          // data: [18203, 23489, 29034],
          itemStyle: {
            normal: {
              color: params => {
                const colorList = ['#4F81BC', '#B8DEE9', '#FFC000', '#00AF50', '#C00000'];
                return colorList[params.dataIndex];
              },
              label: {
                show: true,
                position: 'right',
                textStyle: { // 数值样式
                  color: 'black',
                  fontSize: 16
                }
              }
            }
          }
        }
      ]
    };
  }

  /**
   * @description 协定方使用排名
   */
  createXiedingfang() {
    this.xiedingfangOptions = {
      tooltip: {
      },
      color: ['#C0504E', '#FFC000', '#01B0F1'],
      grid: {
        left: '2%',
        right: '16%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        boundaryGap: [0, 0.01],
        show: false
      },
      yAxis: {
        type: 'category',
        splitLine: { show: false }, // 改设置不显示坐标区域内的y轴分割线
        // data: ['配伍禁忌', '药物超标', '药物重复'],
        axisTick: {
          show: false
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#000',
            fontSize: 16
          }
        },
        data: this.resultsObj['协定方使用排名'].name
      },
      series: [
        {
          type: 'bar',
          barWidth: 30,
          data: this.resultsObj['协定方使用排名'].data,
          // data: [18203, 23489, 29034],
          itemStyle: {
            normal: {
              color: params => {
                const colorList = ['#4F81BC', '#B8DEE9', '#FFC000', '#00AF50', '#C00000'];
                return colorList[params.dataIndex];
              },
              label: {
                show: true,
                position: 'right',
                textStyle: { // 数值样式
                  color: 'black',
                  fontSize: 16
                }
              }
            }
          }
        }
      ]
    };
  }

    /**
   * @description 经典方使用排名
   */
  createJingdianfang() {
    this.jingdianfangOptions = {
      tooltip: {
      },
      color: ['#C0504E', '#FFC000', '#01B0F1'],
      grid: {
        left: '2%',
        right: '16%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        boundaryGap: [0, 0.01],
        show: false
      },
      yAxis: {
        type: 'category',
        splitLine: { show: false }, // 改设置不显示坐标区域内的y轴分割线
        // data: ['配伍禁忌', '药物超标', '药物重复'],
        axisTick: {
          show: false
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#000',
            fontSize: 16
          }
        },
        data: this.resultsObj['经典方使用排名'].name
      },
      series: [
        {
          type: 'bar',
          barWidth: 30,
          data: this.resultsObj['经典方使用排名'].data,
          // data: [18203, 23489, 29034],
          itemStyle: {
            normal: {
              color: params => {
                const colorList = ['#4F81BC', '#B8DEE9', '#FFC000', '#00AF50', '#C00000'];
                return colorList[params.dataIndex];
              },
              label: {
                show: true,
                position: 'right',
                textStyle: { // 数值样式
                  color: 'black',
                  fontSize: 16
                }
              }
            }
          }
        }
      ]
    };
  }

      /**
   * @description 名贵药物排名
   */
  createMingguiyao() {
    this.mingguiyaoOptions = {
      tooltip: {
      },
      color: ['#C0504E', '#FFC000', '#01B0F1'],
      grid: {
        left: '2%',
        right: '16%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        boundaryGap: [0, 0.01],
        show: false
      },
      yAxis: {
        type: 'category',
        splitLine: { show: false }, // 改设置不显示坐标区域内的y轴分割线
        // data: ['配伍禁忌', '药物超标', '药物重复'],
        axisTick: {
          show: false
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#000',
            fontSize: 16
          }
        },
        data: this.resultsObj['名贵药物排名'].name
      },
      series: [
        {
          type: 'bar',
          barWidth: 30,
          data: this.resultsObj['名贵药物排名'].data,
          // data: [18203, 23489, 29034],
          itemStyle: {
            normal: {
              color: params => {
                const colorList = ['#4F81BC', '#B8DEE9', '#FFC000', '#00AF50', '#C00000'];
                return colorList[params.dataIndex];
              },
              label: {
                show: true,
                position: 'right',
                textStyle: { // 数值样式
                  color: 'black',
                  fontSize: 16
                }
              }
            }
          }
        }
      ]
    };
  }


  ngOnInit() {
    this.getKeshi();
    this.getYisheng();
    this.getFuijing();
    this.getYaoxing();
    this.onSubmit();
  }

}
